<?php

namespace App\Http\Controllers;

use Log;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Config;
use Qiniu\Auth;
use App\Models\AppVersion;
use App\Models\Resource;
use App\Utils\ReturnUtils;
use App\Cache\BaseCache;
use App\Models\BaseModel;
use App\Utils\CommonUtils;
use Cache;

class SysController extends Controller {

    public function readLogs(Request $request) {
        $info['page'] = $request->input('page', '1');
        $info['day'] = $request->input('day', '0000000');
        $info['file'] = $request->input('file');
        //读取当日日志
        //发送get请求
        if ($info['page'] < 1) {
            return 'Error page';
        }
        if($info['file'] == 'workman'){
            $filename = __DIR__ . '/../../Service/workman/logs/workman.log';
            if (!file_exists($filename)) {
                echo $filename . '日志文件不存在';
                Log::info($filename . '日志文件不存在');
                return;
            }
        } else {
             $filename = __DIR__ . '/../../../storage/logs/lumen-' . date("Y-m-d", time() - $info['day'] * 24 * 60 * 60) . '.log';
            if (!file_exists($filename)) {
                echo $filename . '日志文件不存在';
                Log::info($filename . '日志文件不存在');
                return;
            }
        }
        $fp = fopen($filename, "r");
        $totalPage = (int) (filesize($filename) / 8192 + 1);
        if ($totalPage < $info['page']) {
            $info['page'] = $totalPage;
        }
        fseek($fp, -8192 * $info['page'], SEEK_END);
        $data = fread($fp, 8192);
        $data = str_replace(' #', '<br>#', $data);
        echo '<pre>';
        echo '<h2>日期：' . date("Y-m-d", time() - $info['day'] * 24 * 60 * 60) . '总共： ' . $totalPage . '页，第' . $info['page'] . '页<br/></h2>';
        echo $data;
    }

    //七牛回调
    public function qiNiu(Request $request) {
        $returnUtils = new ReturnUtils($request);
        $attachment = new Attachment();
        $info = $request->all();
        Log::info(json_encode($info));
        return $returnUtils->returnOk($returnUtils->return['SUCCESS'], $info);
    }

    //获取七牛token
    public function qiNiuUpToken(Request $request) {
        $returnUtils = new ReturnUtils($request);
        $accessKey = env('QINIU_ACCESS_KEY');
        $secretKey = env('QINIU_SECRET_KEY');
        $bucket = env('QINIU_BUCKET');
        $callbackBody = env('QINIU_CALLBACK_BODY');
        $callbackUrl = env('HTTP_HOST') . env('QINIU_CALLBACK');
        $data = array();
        $data['upToken'] = $this->getUptoken($accessKey, $secretKey, $bucket, $callbackUrl, $callbackBody);
        return $returnUtils->returnOk($returnUtils->return['SUCCESS'], $data);
    }

    /*
     * 获取七牛Token
     */

    public function getUptoken($accessKey, $secretKey, $bucket, $callbackUrl, $callbackBody) {
        //获取qiniu配置
        $auth = new Auth($accessKey, $secretKey);
        $key = null;
        $expires = 3600;
        $policy = array(
            'CallbackUrl' => $callbackUrl,
            'CallbackBody' => $callbackBody,
        );
        $strictPolicy = FALSE;
        $token = $auth->uploadToken($bucket, $key, $expires, $policy, $strictPolicy);
        return $token;
    }

    public function getConfig(Request $request) {
        $returnUtils = new ReturnUtils($request);
        $configCache = new BaseCache();
        $configCache->method = 'get';
        $configCache->cacheName = 'config';
        $configCache->cachePar = array($request->input('ty')); //集合
        $retConfigCache = $configCache->HandleCache();
        if (isset($retConfigCache['versionInfo'])) {
            $returnUtils->returnOk($returnUtils->return['SUCCESS'], $retConfigCache);
        }
        // 获取七牛配置
        $accessKey = env('QINIU_ACCESS_KEY');
        $secretKey = env('QINIU_SECRET_KEY');
        $bucket = env('QINIU_BUCKET');
        $callbackBody = env('QINIU_CALLBACK_BODY');
        $callbackUrl = env('HTTP_HOST') . env('QINIU_CALLBACK');
        $data = array();
        $data['qiNiuInfo']['upToken'] = $this->getUptoken($accessKey, $secretKey, $bucket, $callbackUrl, $callbackBody);
        $data['qiNiuInfo']['bucket'] = $bucket;
        $data['qiNiuInfo']['qiNiuHost'] = env('QINIU_HOST_NO_HTTP');
        $updateInfo = array();
        $updateInfo['version'] = '1.0.0';
        $updateInfo['mustUpdate'] = 0; //0 不需要更新 1 需要更新
        $updateInfo['description'] = '默认值';
        $updateInfo['url'] = '';
        if ($request->input('ty') == 'i') {
            $updateInfoIndex = with(new AppVersion($request))->getIosAppVersion();
            if ($updateInfoIndex) {
                $updateInfo = $updateInfoIndex;
            }
        } else if ($request->input('ty') == 'a') {
            $updateInfoIndex = with(new AppVersion($request))->getAndroidAppVersion();
            if ($updateInfoIndex) {
                $updateInfo = $updateInfoIndex;
            }
        } else if ($request->input('ty') == 'tv') {
            $updateInfoIndex = with(new AppVersion($request))->getAndroidAppVersion();
            if ($updateInfoIndex) {
                $updateInfo = $updateInfoIndex;
            }
        }
        $data['liveConfig'] = array('ip' => env('WEBSOCKET_IP'), 'port' => env('WEBSOCKET_PORT'));
        $data['versionInfo'] = $updateInfo;
        $data['other'] = array(
            'sendLogRate' => 2,
        );
        $configCache->method = 'put';
        $configCache->cacheValue = $data;
        $configCache->HandleCache();
        return $returnUtils->returnOk($returnUtils->return['SUCCESS'], $data);
    }

    //获取启动页
    public function getStartupHomepage(Request $request) {
        $returnUtils = new ReturnUtils($request);
        $data = with(new Resource())->getStartupHomepage();
        return $returnUtils->returnOk($returnUtils->return['SUCCESS'], $data);
    }

    //获取启动页
    public function snycDBModel(Request $request) {
        $returnUtils = new ReturnUtils($request);
        with(new BaseModel($request))->snycDBModel();
        return $returnUtils->returnOk($returnUtils->return['SUCCESS']);
    }

    //获取启动页
    public function sendLogsToServer(Request $request) {
        $v = $request->input('v');
        $dk = $request->input('dk');
        $ty = $request->input('ty');
        $logs_jsonstr = $request->input('logs');
        //解析$info，
        if (!isset($logs_jsonstr) || !$logs_jsonstr) {
            return;
        }
        $logs = json_decode($logs_jsonstr, TRUE);
        $userId = -1;
        $verStr = ',v:' . $v . ',dk:' . $dk . ',ty:' . $ty . "\r\n";
        //app启动日志
        if (isset($logs['appStart'])) {
            $logStr = '';
            foreach ($logs['appStart'] as $key => $val) {
                if (isset($val['userId'])) {
                    $userId = with(new CommonUtils())->getId($val['userId']);
                }
                $logStr = $logStr . 'userId:' . $userId . ',beginTime:' . $val['beginTime'] . ',endTime:' . $val['endTime'] . $verStr;
            }
            $ret = $this->writeLogs($logStr, storage_path() . '/client_log/login/');
            if (!$ret) {
                Log::info('写login日志错');
            }
        }
        //写直播日志
//           "from": "value”,//1、轮播 2、精选 3、分类 4、相关推荐 5、机构页面  6、退出播放推荐   7、退出app 推荐  8、历史记录  9、收藏  10 推送
//                    "categoryType": 2,//from = 2 3 时候，/分类类型：1、普通分类 2、正在直播 3、直播预告 4、排行榜 5、媒体专区 6、本地同城
//                    “categoryId": 1,//from = 2 3 时候 分类id， 
//                    "position": 0,//当前直播位置 
//                    "liveStatus": 1,//当前直播直播状态  1、预告 2、直播中 3、回顾
//                    "time": 12345, //点击时间
//                    "userId": “value”//登陆用户用户id
        
        if (isset($logs['live']) && is_array($logs['live'])) {
            foreach ($logs['live'] as $key => $live) {
                $liveId = -1;
                if (isset($live['id'])) {
                    $liveId = with(new CommonUtils())->getId($live['id']);
                    
                }
                if(!$liveId || $liveId == -1){
                    continue;
                }
//            clickLog
                if (isset($live['clickLog'])) {
                    $logStr = '';
                    foreach ($live['clickLog'] as $key => $val) {
                        $userId = -1;
                        if (isset($val['userId'])) {
                            $userId = with(new CommonUtils())->getId($val['userId']);
                        }
                        $logStr = $logStr . 'liveId:' . $liveId . ',from:' . $val['from'] . ',categoryType:' . $val['categoryType'] . ',categoryId:' . $val['categoryId'] . ',position:' . $val['position'] . ',liveStatus:' . $val['liveStatus'] . ',time:' . $val['time'] . ',userId:' . $userId . $verStr;
                    }
                    $ret = $this->writeLogs($logStr, storage_path() . '/client_log/live/click/');
                    if (!$ret) {
                        Log::info('写liveclick日志错');
                    }
                }
                if (isset($live['playLog'])) {
                    $logStr = '';
                    foreach ($live['playLog'] as $key => $val) {
                        $userId = -1;
                        if (isset($val['userId'])) {
                            $userId = with(new CommonUtils())->getId($val['userId']);
                        }
                        $logStr = $logStr . 'liveId:' . $liveId . ',liveStatus:' . $val['liveStatus'] . ',style:' . $val['style'] . ',startTime:' . $val['startTime'] . ',endTime:' . $val['endTime'] . ',userId:' . $userId . $verStr;
                    }
                    $ret = $this->writeLogs($logStr, storage_path() . '/client_log/live/playLog/');
                    if (!$ret) {
                        Log::info('写playLog日志错');
                    }
                }
            }
        }

        if (isset($logs['organization'])&& is_array($logs['organization']) ) {
           
            foreach ($logs['organization'] as $key => $organization) {
                $orgId = -1;
                if (isset($organization['id'])) {
                    $orgId = with(new CommonUtils())->getId($organization['id']);
                }
                if(!$orgId || $orgId == -1){
                    continue;
                }
                $logStr = '';
                if (isset($organization['clickLog'])) {
                    foreach ($organization['clickLog'] as $key => $val) {
                        $logStr = $logStr . 'from:' . $val['from'] . ',startTime:' . $val['startTime'] . ',endTime:' . $val['endTime'] . ',userId:' . $userId . $verStr;
                    }
                }
                $ret = $this->writeLogs($logStr, storage_path() . '/client_log/organization/');
                if (!$ret) {
                    Log::info('写organization日志错');
                }
            }
        }
        if (isset($logs['remain'])&& is_array($logs['remain']) ) {
            $logStr = '';
            foreach ($logs['remain']as $key => $val) {
                $userId = -1;
                if (isset($val['userId'])) {
                    $userId = with(new CommonUtils())->getId($val['userId']);
                }
                $logStr = $logStr . 'type:' . $val['type'] . ',categoryId:' . $val['categoryId'] . ',startTime:' . $val['startTime'] . ',endTime:' . $val['endTime'] . ',userId:' . $userId . $verStr;
            }
            $ret = $this->writeLogs($logStr, storage_path() . '/client_log/remain/');
            if (!$ret) {
                Log::info('写remain日志错');
            }
        }
    }

    //写日志文件
    public function writeLogs($logStr, $fileDir) {
        if (!$fileDir || !$logStr) {
            return false;
        }
        $fileName = $fileDir . 'log_' . date("Y-m-d") . '.log';
        //login_log写入文件
        if (!is_dir($fileDir)) {
            mkdir($fileDir, 0777, TRUE);
        }
        $fp = fopen($fileName, 'a');
        if ($fp) {
            $ret = fwrite($fp, $logStr);
            if (!$ret) {
                Log::info('fopen' . $fileDir . "\\" . $fileName . 'fail');
                return false;
            }
            fclose($fp);
        } else {
            return false;
        }
        return true;
    }

}
